<template>
    <div :style="{ width: width, height: height }">
        <div :style="{ width: width, height: height }" ref="domRef"></div>
    </div>
</template>
<script lang="ts">
import echarts from './importEcharts'
import { ResizeObserver } from '@juggle/resize-observer'

export default defineComponent({
    name: 'base-echarts',
    props: {
        width: {
            type: String,
            default: '100%',
        },
        height: {
            type: String,
            default: '100%',
        },
        options: {
            type: Object,
            default: null,
        },
    },
    setup(props) {
        const domRef = ref(null)
        let chartObj: echarts.ECharts | null = null
        let resizeObserver: ResizeObserver | null = null
        let isInResizeObserver = false // 第一次的resize不需要
        const resizeCallBack = () => {
            if (isInResizeObserver) {
                if (chartObj) {
                    chartObj.resize()
                }
                return
            }
            isInResizeObserver = true
        }

        onMounted(() => {
            if (!chartObj && domRef.value) {
                chartObj = echarts.init(domRef.value)
            }

            if (props.options && chartObj) {
                chartObj.setOption(props.options)
            }

            if (domRef.value) {
                resizeObserver = new ResizeObserver(resizeCallBack)
                resizeObserver.observe(domRef.value)
            }
        })

        onUnmounted(() => {
            if (chartObj) {
                chartObj.dispose()
                chartObj = null
            }
            if (resizeObserver && domRef.value) {
                resizeObserver.disconnect()
                resizeObserver.unobserve(domRef.value)
            }
        })

        watch(
            () => props.options,
            () => {
                if (chartObj) {
                    chartObj.setOption(props.options)
                }
            },
        )

        return {
            domRef,
        }
    },
})
</script>
